﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;

namespace SAE.Plugin.Demo
{
    public class ExportSiteStructure : SPSAdminJob
    {
        protected override int OnRun(object parameter)
        {
            if (parameter is SPSite)
            {
                base.TotalProgressMaximumStep = (parameter as SPSite).AllWebs.Count;

                XmlDocument xDoc = new XmlDocument();
                SPWeb rootWeb = (parameter as SPSite).RootWeb;
                XmlNode rootNode = xDoc.CreateNode(XmlNodeType.Element, XmlConvert.EncodeName(rootWeb.Title), rootWeb.ServerRelativeUrl);
                xDoc.AppendChild(rootNode);
                ReViewChildWeb(rootWeb, rootNode);

                xDoc.Save("sitestructure.xml");
            }

            return 1;
        }

        void ReViewChildWeb(SPWeb web,XmlNode webNode)
        {
            foreach (SPWeb childWeb in web.Webs)
            {
                string title = XmlConvert.EncodeName(childWeb.Title);
                XmlNode childWebNode = webNode.OwnerDocument.CreateNode(XmlNodeType.Element, title, childWeb.ServerRelativeUrl);
                webNode.AppendChild(childWebNode);
                
                ReportCurrentProgress(1, childWebNode.Name);

                ReViewChildWeb(childWeb, childWebNode);
            }
        }
    }
}
